package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private CacheClient cacheClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {

        // 缓存穿透解决方案：redis存空值
        Shop shop = queryWithPassThrough(id);

        // 缓存击穿解决方案：互斥锁
        // Shop shop = queryWithMutex(id);

        // 缓存击穿解决方案：逻辑过期
//        Shop shop = queryLogicTTL(id);

        // 最终版本 封装了Redis工具方法 调用解决缓存穿透的方法
//        Shop shop = cacheClient.handleCachePenetration(CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//
//        log.info("getShop:" + shop);
//        if (Objects.isNull(shop)) {
//            return Result.fail("店铺不存在");
//        }

        // 调用解决缓存击穿的方法
//        Shop shop = cacheClient.handleCacheBreakdown(CACHE_SHOP_KEY, id, Shop.class,
//                this::getById, CACHE_SHOP_TTL, TimeUnit.SECONDS);
//        if (Objects.isNull(shop)) {
//            return Result.fail("店铺不存在");
//        }
        return Result.ok(shop);
    }


    // 解决缓存穿透问题
    public Shop queryWithPassThrough(Long id){
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 判断是否存在 存在则返回
        if(StrUtil.isNotBlank(shopJson)){
            log.info("shop exist in  Redis");
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }


        if(shopJson != null && shopJson.equals("")){
            // 说明 返回的shopJson是一个用以解决缓存穿透的""字符串
            return null;
        }

        // 不存在就查数据库
        Shop shop = this.getById(id);
        if(shop == null){
            log.info("不存在商户, id:" + id);
            // 添加空值null进入Redis 解决缓存穿透问题
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        log.info("查询到shop");

        //存在就把他添加到Redis缓存里 并返回
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    // 利用互斥锁 解决缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在 存在则返回
        if(StrUtil.isNotBlank(shopJson)){
            log.info("shop exist in  Redis");
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        if(shopJson != null && shopJson.equals("")){
            // 说明 返回的shopJson是一个用以解决缓存穿透的""字符串
            return null;
        }

        // 解决缓存击穿
        String mutexKey = "lock:shop:" + id;
        Shop shop = null;
        int spinCount = 0;
        final int maxSpins = 20; // 最大自旋次数
        final long spinInterval = 50; // 自旋间隔时间(ms)

        try {
            // 自旋锁尝试拿锁
            while (!tryLock(mutexKey)) {
                if (++spinCount > maxSpins) {
                    log.warn("获取锁失败，已达到最大自旋次数: {}", maxSpins);
                    return null; // 或者可以返回旧数据/降级处理
                }
                Thread.sleep(spinInterval); // 短暂休眠后继续尝试
            }
            // 拿锁成功
            shop = this.getById(id);
            if(shop == null){
                log.info("不存在商户, id:" + id);
                // 添加空值null进入Redis 解决缓存穿透问题
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }

            log.info("查询到shop");
            //存在就把他添加到Redis缓存里 并返回
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(mutexKey);
        }
        return shop;
    }



    private static final ExecutorService CACHE_REBUILD_POOL = Executors.newFixedThreadPool(10);

    // 缓存击穿解决方法2 逻辑过期设置
    public Shop queryLogicTTL(Long id) {

        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 判断是否存在 这里为了方便演示，不存在返回null
        if(StrUtil.isBlank(shopJson)){
            log.info("shop not exist in Redis");
            return null;
        }

        // 如果存在缓存 需要判断是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject)redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        // 判断是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            // 未过期 返回
             return shop;
        }

        // 逻辑过期 需要缓存重建

        String mutexKey = "lock:shop:" + id;
        int spinCount = 0;
        final int maxSpins = 20; // 最大自旋次数
        final long spinInterval = 50; // 自旋间隔时间(ms)

        try {
            // 自旋锁尝试拿锁
            while (!tryLock(mutexKey)) {
                if (++spinCount > maxSpins) {
                    log.warn("获取锁失败，已达到最大自旋次数: {}", maxSpins);
                    return null; // 或者可以返回旧数据/降级处理
                }
                Thread.sleep(spinInterval); // 短暂休眠后继续尝试
            }
            // 拿锁成功 使用线程进行缓存重建
            CACHE_REBUILD_POOL.submit(() -> {
                this.saveShop2Redis(id, 30L);
            });
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(mutexKey);
        }
        // 缓存重建完成后 这里不需要再获取新的shop 这里接收旧的shop数据
        return shop;
    }

            private boolean tryLock(String key){
                // 基于Redis的setnex实现互斥锁
                Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
                return BooleanUtil.isTrue(flag);
            }

            private boolean unlock(String key){
                Boolean flag = stringRedisTemplate.delete(key);
                return BooleanUtil.isTrue(flag);
            }

    @Override
    public Result updateShopById(Shop shop) {
        // 两步骤 1更新数据库 2删除缓存
        // 参数校验, 略

        // 1、更新数据库中的店铺数据
        boolean f = this.updateById(shop);
        if (!f) {
            // 缓存更新失败，抛出异常，事务回滚
            throw new RuntimeException("数据库更新失败");
        }
        // 2、删除缓存
        f = stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        if (!f) {
            // 缓存删除失败，抛出异常，事务回滚
            throw new RuntimeException("缓存删除失败");
        }
        return Result.ok(shop);
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if(x == null || y == null){
            Page<Shop> page = this.query().eq("type_id", typeId).page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        // 2.1 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 2.2 根据经纬度从redis中查询店铺数据，并按照距离排序、分页
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate
                .opsForGeo().search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        // 默认搜索范围是5km
                        new Distance(5000),
                        // 查询从0到end，所以后面还需要截取from到end之间的数据
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results == null) {
            // 缓存中不存在店铺数据
            return Result.ok(Collections.emptyList());
        }
        // 4.2 缓存中存在店铺数据，则需要截取 from ~ end的部分，需要判断from到end之间的数据是否存在
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 当前数据比起始索引还要小，说明没有我们要查询页的数据
            return Result.ok(Collections.emptyList());
        }
        // 4.3 from到end之间的数据存在，则解析出店铺id
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        // skip表示直接从第from个数据开始遍历
        list.stream().skip(from).forEach(result -> {
            // 获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取店铺距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });

        // 5、根据店铺ids查询出店铺数据
        String idStr = StrUtil.join(",", ids);
        // 5.1 查寻出所有符合条件的店铺数据（这里需要利用ORDER BY FIELD确保id的有序性）
        List<Shop> shopList = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
//        List<Shop> shopList = this.list(new LambdaQueryWrapper<Shop>()
//                .in(Shop::getId, ids)
//                .last("ORDER BY FIELD(id," + idStr + ")"));
        // 5.2 为店铺的距离属性进行赋值
        for (Shop shop : shopList) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        // 6、返回
        return Result.ok(shopList);
    }

    // 数据预热
    public void saveShop2Redis(Long id, Long expireSeconds){
        Shop shop = this.getById(id);
        log.info("查询到shop");
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }
}
